package com.zwl.springcloud.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zwl.springcloud.annotation.EnableAuth;
import com.zwl.springcloud.dao.OrderMapper;
import com.zwl.springcloud.dao.UserMapper;
import com.zwl.springcloud.entity.Order;
import com.zwl.springcloud.entity.Result;
import com.zwl.springcloud.entity.User;
import com.zwl.springcloud.pojo.CreateOrderDTO;
import com.zwl.springcloud.utlis.TokenUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/** @date 2022/02/19
 *
 * 订单控制类
 * */
@RequestMapping("/v1/order")
@RestController
public class OrderController {
    @Resource private UserMapper userMapper;

    @Resource private OrderMapper orderMapper;
    /*
     * 创建订单
     * */
    @PostMapping("/create")
    @EnableAuth
    public Result<Object> createOrder(@RequestBody CreateOrderDTO createOrderDTO, HttpServletRequest request) {
        Order order = new Order();
        BeanUtils.copyProperties(createOrderDTO, order);
        order.setStateId(0);
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());

        String username = TokenUtil.getAccount(request.getHeader("admin-token"));
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username));
        if (user == null) {
            return new Result<>("请先登录");
        }
        order.setCreateUserId(user.getUserId());
        orderMapper.insert(order);
        return new Result<>(true);
    }

    @GetMapping("/{id}")
    public Result<Order> getOrderById(@PathVariable("id") Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return new Result<>("订单不存在", 500, null);
        }

        if (order.getExpiredAt().before(new Date())) {
            order.setStateId(3);
            orderMapper.updateById(order);
        }

        return new Result<>(order);
    }
}
